/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.distribution.multishop.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.comment.model.DistributionProd;
import com.yami.shop.distribution.comment.model.DistributionProdLog;
import com.yami.shop.distribution.comment.service.DistributionProdService;
import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/distribution/distributionProd")
@AllArgsConstructor
public class DistributionProdController {

    private final DistributionProdService distributionProdService;

    private final OfflineHandleEventService offlineHandleEventService;

    private final ProductService productService;

    @GetMapping("/count")
    public ResponseEntity<Integer> count(Long prodId) {
        return ResponseEntity.ok(distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, prodId)
        ));
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<DistributionProd>> page(DistributionProd distributionProd, PageParam<DistributionProd> page, String prodName, Integer state) {
        distributionProd.setShopId(SecurityUtils.getShopUser().getShopId());
        distributionProd.setState(state);
        IPage<DistributionProd> list = distributionProdService.distributionProdsPage(page, distributionProd, prodName);
        return ResponseEntity.ok(list);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
    public ResponseEntity<DistributionProd> info(@PathVariable("id") Long id) {
        DistributionProd distributionProd = distributionProdService.getById(id);
        return ResponseEntity.ok(distributionProd);
    }

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionProd:save')")
    public ResponseEntity<Void> save(@RequestBody @Valid DistributionProd distributionProd) {
        distributionProd.setShopId(SecurityUtils.getShopUser().getShopId());
        // 防止重复提交
        int count = distributionProdService.count(new LambdaQueryWrapper<DistributionProd>()
                .eq(DistributionProd::getProdId, distributionProd.getProdId())
                .eq(DistributionProd::getShopId, distributionProd.getShopId()));
        if (count>0){
            // 分销商品已经存在
            throw new YamiShopBindException("yami.distribution.prod.exist");
        }
        // 校验数据
        validateDistributionProd(distributionProd);
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.save(distributionProd);
        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionProd:update')")
    public ResponseEntity<Void> update(@RequestBody @Valid DistributionProd distributionProd) {
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        // 校验数据
        validateDistributionProd(distributionProd);

        if (!Objects.equals(distributionProd.getShopId(), shopUser.getShopId())) {
            //没有权限
            throw new UnauthorizedException("yami.no.auth");
        }
        setDefaultAwardNumbers(distributionProd);
        distributionProdService.updateById(distributionProd);
        distributionProdService.removeDistributionProdPOCacheByProdId(distributionProd.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionProd:delete')")
    public ResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionProdService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }


    private void setDefaultAwardNumbers(@Valid @RequestBody DistributionProd distributionProd) {
        if (StrUtil.isBlank(distributionProd.getParentAwardNumbers())) {
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setParentAwardNumbers("0");
            } else {
                distributionProd.setParentAwardNumbers(null);
            }
        }
        if (StrUtil.isBlank(distributionProd.getAwardNumbers())) {
            distributionProd.setAwardNumbers("0");
            // 固定奖励
            if (Objects.equals(distributionProd.getAwardNumberSet(), 0)) {
                distributionProd.setAwardNumbers("0");
            } else {
                distributionProd.setAwardNumbers(null);
            }
        }
        distributionProd.setUpdateTime(new Date());
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineEventByDistProdId/{distributionProdId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineEventByDistProdId(@PathVariable("distributionProdId") Long distributionProdId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISTRIBUTION_PROD.getValue(), distributionProdId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    @PreAuthorize("@pms.hasPermission('distribution:distributionProd:auditApply')")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        DistributionProd distributionProd = distributionProdService.getById(offlineHandleEventAuditParam.getHandleId());
        if (distributionProd == null) {
            // 未找到分销商品信息信息
            throw new YamiShopBindException("yami.distribution.prod.exist.error");
        }
        distributionProdService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ResponseEntity.ok().build();
    }

    /**
     * 获取分销商品销售记录信息
     */
    @GetMapping("/getDistributionProdLogPage")
    public ResponseEntity<IPage<DistributionProdLog>> getDistributionProdLogPage(DistributionProdLog distributionProdLog, PageParam<DistributionProdLog> page) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        distributionProdLog.setShopId(shopId);
        IPage<DistributionProdLog> distributionProdLogL = distributionProdService.getDistributionProdLogPage(page,distributionProdLog);
        return ResponseEntity.ok(distributionProdLogL);
    }

    /**
     * 校验数据
     */
    private void validateDistributionProd(DistributionProd distributionProd) {
        Product product = productService.getProductByProdId(distributionProd.getProdId(), I18nMessage.getDbLang());
        if (product == null) {
            // 未找到此商品
            throw new YamiShopBindException("yami.product.not.exist");
        }
        // 如果不使用需要校验
        if (distributionProd.getDefaultReward() == 1) {
            return;
        }

        // 按比例
        if (distributionProd.getAwardProportion() == 0) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getAwardNumbers()) >= 100) {
                    // 固定奖励比例设置不能超过100%
                    throw new YamiShopBindException("yami.distribution.prod.award");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > 100)) {
                    // 等级奖励比例设置不能超过100%
                    throw new YamiShopBindException("yami.distribution.prod.level");
                }
            }

        }
        // 按金额
        if (distributionProd.getAwardProportion() == 1) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getAwardNumbers()) > product.getPrice()) {
                    // 固定奖励设置不能超商品的原价格
                    throw new YamiShopBindException("yami.distribution.prod.award.check");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > product.getPrice())) {
                    // 等级奖励设置不能超商品的原价格
                    throw new YamiShopBindException("yami.distribution.prod.level.check");
                }
            }
        }
        // 查看是否有开启邀请人奖励
        if (distributionProd.getParentAwardSet() == 0) {
            return;
        }

        // 按比例
        if (distributionProd.getAwardProportion() == 0) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getParentAwardNumbers()) >= 100) {
                    // 邀请人固定奖励比例设置不能超过100%
                    throw new YamiShopBindException("yami.distribution.prod.parent.award");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getParentAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > 100)) {
                    // 邀请人等级奖励比例设置不能超过100%
                    throw new YamiShopBindException("yami.distribution.prod.parent.level");
                }
            }

        }
        // 按金额
        if (distributionProd.getAwardProportion() == 1) {
            // 奖励数额设置(0 固定奖励,1 根据等级奖励)
            if (distributionProd.getAwardNumberSet() == 0) {
                if (Double.parseDouble(distributionProd.getParentAwardNumbers()) > product.getPrice()) {
                    // 邀请人固定奖励设置不能超商品的原价格
                    throw new YamiShopBindException("yami.distribution.prod.parentAward.check");
                }
            }
            if (distributionProd.getAwardNumberSet() == 1) {
                List<String> awardList = JSONUtil.parseArray(distributionProd.getParentAwardNumbers()).toList(String.class);
                List<Double> list = awardList.stream().map(Double::parseDouble).collect(Collectors.toList());
                if (list.stream().anyMatch(item -> item > product.getPrice())) {
                    // 邀请人等级奖励设置不能超商品的原价格
                    throw new YamiShopBindException("yami.distribution.prod.parentLevel.check");
                }
            }
        }
    }
}
